package com.zyf.chapter02.behavior.observer.eventbus.p2p;


import com.zyf.chapter02.behavior.observer.eventbus.AsyncEventBus;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author yifeng
 */
public class UserController {
    private UserService userService = new UserService();
    private PromotionService promotionService = new PromotionService();

    private static AsyncEventBus eventBus;
    private static ExecutorService executor = Executors.newCachedThreadPool();

    static {
        eventBus = new AsyncEventBus(executor);
        eventBus.register(new UserListener());
    }

    /**
     * 提供用户注册的功能，用户注册成功之后会给用户发放投资体验金
     * <p>
     * 存在的问题，违反单一职责原则，如果需求频繁变动，就需要频繁修改 register，违反开闭原则
     * @param telephone 手机号
     * @param password 密码
     * @return 自动生成的 uesrId
     */
    public Long register(String telephone, String password) {
        // 省略输入参数的校验代码
        // 省略 userService.register() 异常的 try-catch代码
        long userId = userService.register(telephone, password);
        eventBus.post(1L);
        return userId;
    }

    public static void main(String[] args) {
        UserController userController = new UserController();
        userController.register("12947302", "238403");
        // 用完线程池记得关闭，否则程序将会一直执行，该代码与 EventBus 无关
        executor.shutdownNow();
    }
}
